import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const WebSocket = require('ws');

// 创建WebSocket服务器
const server = new WebSocket.Server({ port: 8086 });
console.log('WebSocket服务器已启动，监听端口8086');
// 当有客户端连接时触发
server.on('connection', (socket, request) => {
  console.log('新的客户端已连接');
  // 当从客户端接收到消息时触发
  socket.on('message', (message) => {
    console.log(`收到消息：${message}`);
    // 向客户端发送消息
  if(message=='Hello, WebSocket Server!'){
    socket.send(JSON.stringify({ message: '欢迎连接到WebSocket服务器！_廖杨林', identity: "you" }));
  }else{
    socket.send(JSON.stringify(message));
  }
  });
  
});
// 启动
// node server.js